package org.jeecg.modules.lab.syn;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class CronSqlJob {

    @Autowired
    private ILabCronJobService labCronJobService;
    @Autowired
    private SynDataUtil synDataUtil;

    @XxlJob(value = "CronSqlJob")
    public ReturnT<String> execute(String params) {
        List<LabCronJob> jobList = labCronJobService.list(new LambdaQueryWrapper<LabCronJob>()
                .eq(LabCronJob::getComplete, "N")
                .orderByAsc(LabCronJob::getTimeStamp)
                .orderByAsc(LabCronJob::getOrderNum));
        if (jobList != null) {
            String formatDateTime = DateUtils.getDate("yyyyMMddHHmmss");
            for (LabCronJob cronJob : jobList) {
                String flag = cronJob.getSynFlag();
                String tableName = cronJob.getTableName();
                String complete = cronJob.getComplete();
                if ("0".equals(flag) && "N".equals(complete)) {
                    //新增
                    synDataUtil.zuZhuangInsertSql(cronJob, formatDateTime);
                    //同一批中相同表名和操作的数据不在提交
                    jobList.forEach(e -> {
                        if (tableName.equals(e.getTableName()) && flag.equals(e.getSynFlag())) {
                            e.setComplete("Y");
                        }
                    });
                } else if ("1".equals(flag) && "N".equals(complete)) {
                    //修改
                    synDataUtil.zuZhuangUpdateSql(cronJob, formatDateTime);
                    jobList.forEach(e -> {
                        if (tableName.equals(e.getTableName()) && flag.equals(e.getSynFlag())) {
                            e.setComplete("Y");
                        }
                    });
                } else if ("2".equals(flag) && "N".equals(complete)) {
                    //删除
                    synDataUtil.zuZhuangDeleteSql(cronJob, formatDateTime);
                    cronJob.setComplete("Y");
                }
            }
            labCronJobService.updateBatchById(jobList);

        }
        return ReturnT.SUCCESS;
    }
}

